/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.odb.bzk3.android;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.Vector;


import br.odb.libscene.SceneObject;

import br.odb.utils.math.Vec3;


/**
 * 
 * @author daniel
 */
public class ObjMesh extends SceneObject {
	private int lastColor;
	private final Random rnd;
	public Vector verteces;
	public ObjMesh() {
		verteces = new Vector();
		lastColor = 0;
		rnd = new Random();
	}

	public void internalize( InputStream filecontent) {
		String Sub = null;
		int pos = 0;
		char head;
		
		try {
			while ( filecontent.available() != 0 ) {
				head = (char) filecontent.read();
				if (pos == 0 || head == '\n') {
					if (Sub != null && Sub.length() > 0) {
						Parse(Sub);
					}
					Sub = new String();
				}
				if (head != '\n') {
					Sub += head;
				}
				pos++;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	String getSubToken(String main, int token) {
		String work = main;
		String toreturn = null;
		while (token > -1) {
			if (token == 0) {
				if (work.indexOf(' ') != -1) {
					toreturn = work.substring(0, work.indexOf(' '));
				} else {
					toreturn = work;
				}
			}

			if (work.indexOf(' ') != -1) {
				work = work.substring(work.indexOf(' ') + 1);
			}

			token--;
		}

		return toreturn;
	}

	int getARGBColor(int i0, int i1, int i2) {
		if (i0 >= 255)
			i0 = 255;
		if (i1 >= 255)
			i1 = 255;
		if (i2 >= 255)
			i2 = 255;

		int color = 0xFF000000;
		{
			color += i0 * 0x10000;
			color += i1 * 0x100;
			color += i2;
		}
		return color;
	}

	private void Parse(String Sub) {
		Vec3 origin = getPosition();
		switch (Sub.charAt(0)) {
		case 'v':
			verteces.addElement(new Vec3(
					origin.x + Float.parseFloat(getSubToken(Sub, 1)), 
					origin.y + Float.parseFloat(getSubToken(Sub, 2)), 
					origin.z + Float.parseFloat(getSubToken(Sub, 3)))
			);
			break;
		case 'c':
			lastColor = this.getARGBColor(
					Integer.parseInt(getSubToken(Sub, 1)),
					Integer.parseInt(getSubToken(Sub, 2)),
					Integer.parseInt(getSubToken(Sub, 3)));
			break;
		case 'f':

			int v = (int) (rnd.nextFloat() * 255);
			lastColor = this.getARGBColor(v, v, v);
			Vec3 v1 = (Vec3) verteces.elementAt(Integer.parseInt(getSubToken(
					Sub, 1)) - 1);
			Vec3 v2 = (Vec3) verteces.elementAt(Integer.parseInt(getSubToken(
					Sub, 2)) - 1);
			Vec3 v3 = (Vec3) verteces.elementAt(Integer.parseInt(getSubToken(
					Sub, 3)) - 1);

			addFace( TriangleFactory.getInstance().makeTrig( 
					v1.x, v1.y, v1.z,  
					v2.x, v2.y, v2.z,  
					v3.x, v3.y, v3.z,		
					lastColor ) );

			break;
		}
	}
}
